﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Diagnostics;
using System.IO;

namespace CFScript.Tasks
{
    /// <summary>
    /// TODO: Update summary.
    /// </summary>
    public class Delete:Task
    {
        public Delete()
        {
            this.name = "<delete>";
            this.parameterNames = new string[] {"path"};
            this.parameterExpandable = new bool[] { true};
            this.parameterRequired = new bool[] {true};
            this.parameters = new Dictionary<string, Parameter>();

            Debug.Assert(this.parameterNames.Length == this.parameterRequired.Length &&
                         this.parameterRequired.Length == this.parameterRequired.Length);
        }

        public override InstructionResult Execute(CFScript context)
        {
            InstructionResult result = new InstructionResult();
            result.ExecutedInstruction = this;

            string fileName = this.parameters["path"].GetValue(context);

            try
            {
                // Let's delete the file

                FileInfo fi = new FileInfo(fileName);

                if (fi.Exists)
                {
                    if((fi.Attributes & FileAttributes.Directory) == FileAttributes.Directory)
                    {
                        // It's a directory
                        Directory.Delete(fileName, true);
                    }
                    else
                    {
                        // It's a single file
                        fi.Delete();
                    }
                    result.Code = ResultCode.OK;
                }
                else
                {
                    // File not present. Can't delete
                    result.Code = ResultCode.WARN;
                    switch (context.Options.VerboseLevel)
                    {
                        case VerboseMode.MINIMUM:
                        case VerboseMode.ALL:
                            result.Message = string.Format("File {0} not found", fileName);
                            break;
                    }
                }
            }
            catch (Exception ex)
            {
                result.Code = ResultCode.ERROR;
                result.Message = ex.Message;
            }
            
            result.BreakExecution = result.Code == ResultCode.ERROR && this.options.OnError == OnErrorAction.BREAK;
            
            return result;
        }

        
    }
}
